package com.ang.juc.nt.longadder;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.atomic.LongAdder;
import java.util.stream.IntStream;

public class LongadderTest {

    private static Long count = 0l;
    private static LongAdder countAdder = new LongAdder();

    public static void main(String[] args) throws InterruptedException {

        //使用Long，结果<1000
//        List<Thread> list1 = new Vector<>();
        List<Thread> list1 = new ArrayList<>();
        IntStream.range(0,10).forEach(i->{
            Thread thread = new Thread(() -> {
                IntStream.range(0, 100).forEach(j -> {
                    count++;
                });
            });

            thread.start();
            list1.add(thread);
        });
        for (Thread thread : list1) {
            thread.join();
        }

        System.out.println("使用Long："+count);

        //LongAdder，结果==1000
//        List<Thread> list2 = new Vector<>();
        List<Thread> list2 = new ArrayList<>();
        IntStream.range(0,10).forEach(i->{
            Thread thread = new Thread(() -> {
                IntStream.range(0, 100).forEach(j -> {
                    countAdder.increment();
                });
            });

            thread.start();
            list2.add(thread);
        });
        for (Thread thread : list2) {
            thread.join();
        }

        System.out.println("使用LongAdder："+countAdder.longValue());

    }
}
